import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Sebastian
 * @version 2.0
 * @date 2024/7/1 20:26
 */
// 组合总和
    // https://leetcode.cn/problems/combination-sum/
public class Solution39 {
    List<List<Integer>> result = new LinkedList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtrack(target, 0, candidates, 0);
        return result;
    }

    LinkedList<Integer> track = new LinkedList<>();
    private void backtrack(int target, int start, int[] candidates, int sum) {
        if (sum == target) {
            // 这里为什么不能直接add
            // result.add(track);
            result.add(new LinkedList<>(track));
            return;
        }
        if (sum > target) return;

        for (int i = start; i < candidates.length; i++) {
            // 选择candidates中的元素
            track.add(candidates[i]);
            sum += candidates[i];
            backtrack(target, i, candidates, sum);
            // 撤销选择
            sum -= candidates[i];
            track.removeLast();
        }
    }
}
